# *---encoding:UTF-8--*
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, execjs, time
from common.helper import Helper
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "瑞华终身重大疾病保险计划"
        self.filename = "commonJS"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "400000", "500000"],
                # 交费方式
                "payType": ["年交"],
                # 交费间隔
                "interval": ["0", "3", "5", "10", "15", "20", "30"],
                # 保障期限
                "expire": ["终身"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "400000"],
                # 交费方式
                "payType": ["年交"],
                # 交费间隔
                "interval": ["0", "3", "5", "10", "15", "20"],
                # 保障期限
                "expire": ["终身"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000"],
                # 交费方式
                "payType": ["年交"],
                # 交费间隔
                "interval": ["0", "3", "5", "10", "15", "20"],
                # 保障期限
                "expire": ["终身"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000"],
                # 交费方式
                "payType": ["年交"],
                # 交费间隔
                "interval": ["0", "3", "5", "10", "15"],
                # 保障期限
                "expire": ["终身"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["payType"],
                             plan[k]["interval"], plan[k]["expire"]):
                if v[4] == "0":

                    payType = "一次交清"

                    tuple_to_list = (list(v))

                    tuple_to_list[3] = payType

                    list_to_tuple = tuple(tuple_to_list)

                    data = Helper.formatProductInfo(plan[k], list_to_tuple)
                else:
                    data = Helper.formatProductInfo(plan[k], v)

                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

        # 获取请求参数

    def RequestJson(self, dt=None,mysql=None):

        sex = "m" if dt["gender"] == "M" else "f"
        interval = "1" if dt["interval"] == "0" else dt["interval"]
        cFinTyp = "0" if interval == "1" else "12"
        data = {
            "transfer": "GTO2OINTERFACE2017#@!%88",
            "payload": '{"base":{"NAmt":"'+dt["money"]+'","CInsuYear":"106","CFinTyp":"'+cFinTyp+'","NPayTime":"'+interval+'","CArea":"310000","CProdNo":"990002","CInsuYearFlag":"A"},"applicant":{"TBirthday":"","CSex":"m"},"insured":{"TBirthday":"'+str(int(2020-int(dt["year"])))+'-01-01","CSex":"'+sex+'","CCusLvl":"1"},"cvrgList":[{"CCvrgNo":"301002","CCustCvrgNme":"重大疾病保险（B款）","NAmt":"'+dt["money"]+'","CProdNo":"300002","CNmeCn":"重大疾病保险（B款）","NDductAmt":""}],"prodList":[{"CProdNo":"300002","CProdName":"瑞华终身重大疾病保险","CFinTyp":"12","NPayTime":"'+interval+'","CInsuYear":"106","CInsuYearFlag":"A","NHsttPrd":15,"NDssWtPrd":180,"CRdrProd":"0","NGrntExtInsr":-2,"CAutoPadding":"1"}]}'
        }

        packJS = open('./' + self.filename + '/packageList.js', mode='r', encoding="utf-8").read()
        cxt = execjs.compile(packJS)
        # 获取packageList参数值
        packageList = cxt.call("genPackageList", data["payload"])
        form_data = '{"packageList":{"packages":{"header":{"requestType":"RHCALCULATION","comId":"GTO2O20170118","from":"iwechat","sendTime":"' + \
                    packageList["packageList"]["packages"]["header"][
                        "sendTime"] + '","orderSerial":"orderId","comSerial":"comSerial"},"request":"' + \
                    packageList["packageList"]["packages"]["request"] + '"}}}'

        signJS = open('./' + self.filename + '/sign.js', mode='r', encoding="utf-8").read()
        cxt = execjs.compile(signJS)
        # 获取加密签名
        sign = cxt.call("hex_hmac_md5", data["transfer"], packageList)
        r = requests.post(url=domain[self.name]["url"] + "sign=" + sign + "&com_id=GTO2O20170118",
                          headers=domain[self.name]["header"], data=form_data)
        if r.status_code == 200 and "cvrgList" not in r.text:
            data = (r.json()["packageList"]["packages"]["response"])

            res = self.responseDecode(data)

            try:

                result = json.loads(res['responsePayload']["data"])
                price = Helper.decimalParse(result["calPremium"]["cvrgList"][0]["NPrm"])
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                print( data )

                mysql.updatePrice(data)
            except Exception as e:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                mysql.updateTask(data)
                print("\n/*产品价格更新失败:%d*/" % dt["id"])

    # 解码
    def responseDecode(self, data):
        JSdecode = open('./' + self.filename + '/decode.js', mode='r', encoding="utf-8").read()
        cxt = execjs.compile(JSdecode)
        response = cxt.call("decrypt", "", data)
        return response

    def main(self,mysql):

        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.RequestJson(dt,mysql)

    # 多线程
    def startProcess(self):
        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()